package com.itheima.tanhua.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.itheima.autoconfig.template.OssTemplate;
import com.itheima.tanhua.api.db.UserInfoServiceApi;
import com.itheima.tanhua.api.mongo.CommentApi;
import com.itheima.tanhua.api.mongo.MovementServiceApi;
import com.itheima.tanhua.exception.ConsumertException;
import com.itheima.tanhua.utils.Constants;
import com.itheima.tanhuan.pojo.db.Friend;
import com.itheima.tanhuan.pojo.db.UserInfo;
import com.itheima.tanhuan.pojo.mongo.Movement;
import com.itheima.tanhuan.pojo.mongo.Visitors;
import com.itheima.tanhuan.vo.mongo.MovementVo;
import com.itheima.tanhuan.vo.mongo.MovementsVo;
import com.itheima.tanhuan.vo.mongo.PageResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MovementService {
    @Autowired
    OssTemplate ossTemplate;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @DubboReference
    MovementServiceApi movementServiceApi;
    @DubboReference
    private UserInfoServiceApi userInfoServiceApi;
    @DubboReference
    CommentApi commentApi;

    /**
     * @param movementVo   分装的前端传来的数据
     * @param imageContent 动图
     * @return
     */
    public boolean movement(MovementVo movementVo, MultipartFile[] imageContent) {
        try {
            //判断文件有没有数据
            if (movementVo.getTextContent() == null) {
                throw new ConsumertException("动图没有数据");
            }

            //1.动态图片上传到sso
            ArrayList<String> list = new ArrayList<>();
            for (int i = 0; i < imageContent.length; i++) {
                String urimage = ossTemplate.upload(imageContent[i].getOriginalFilename(), imageContent[i].getInputStream());
                list.add(urimage);
            }
            //2.保存动态
            Movement movement = new Movement();
            BeanUtil.copyProperties(movementVo, movement);
            movement.setCreated(System.currentTimeMillis());
            movement.setMedias(list);
            movement.setLocationName(movementVo.getLocation());
            String uid = stringRedisTemplate.opsForValue().get("UID");
            movement.setUserId(Convert.toLong(uid));
            //调用远程方法
            return movementServiceApi.publish(movement);
        } catch (IOException e) {
            throw new ConsumertException("发布失败");
        }


    }
//我的好友动态
    public PageResult all(Integer page, Integer pagesize, Long userId) {
        //1.查询好友列表
//        List<Long> friendIds = new ArrayList<>();
//        friendIds.add(106l);
        List<Friend> friendList = movementServiceApi.friendById(userId);
        List<Long>friendIds=new ArrayList<>();
        for (Friend friend : friendList) {
            friendIds.add(friend.getFriendId());
        }

        List<MovementsVo>list=new ArrayList<>();
        //2. 动态
        for (Long friendId : friendIds) {
            //2.1 生成每一个动态
            UserInfo userInfo = userInfoServiceApi.findById(friendId);
                //2.1.1动态集合
                List<Movement> fmove = movementServiceApi.getMove(friendId, page, pagesize);
            for (Movement movement : fmove) {
                MovementsVo movementsVo = MovementsVo.init(userInfo, movement);
                list.add(movementsVo);
            }
            }
        PageResult pageResult=new PageResult(page,pagesize,list);
        pageResult.setCounts(list.size());
        pageResult.setPages(list.size()/pagesize);
        return pageResult;
        }

    /**
     *
     * @param userId 用户id
     * @param page 页面大小
     * @param pagesize 页面规格
     * @return
     */
    public ResponseEntity myMove(Long userId, Integer page, Integer pagesize) {
        List<MovementsVo> list=new ArrayList<>();
        //1. 查询自己的个人信息

        //2. 判断动态有无，分装对象
        List<Movement> move = movementServiceApi.getMove(userId,page,pagesize);
        if (move==null){
            return ResponseEntity.ok(new PageResult(page,pagesize));
        }
        UserInfo userInfo = userInfoServiceApi.findById(userId);
        //3. 查询动态信息
        for (Movement movement : move) {
            MovementsVo init = MovementsVo.init(userInfo, movement);
            if (ObjectUtil.isEmpty(init.getLoveCount())){init.setLoveCount(0);}
            if (ObjectUtil.isEmpty(init.getCommentCount())){init.setCommentCount(0);}
            if (ObjectUtil.isEmpty(init.getLikeCount())){init.setLikeCount(0);}
            list.add(init);
        }
        PageResult pageResult=new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setCounts(list.size());
        pageResult.setPages(pageResult.getCounts()/pagesize);

        pageResult.setItems(list);

/*        //谁查看了我，保存数据
        //看有没有这个数据
        Long visitor = Convert.toLong(stringRedisTemplate.opsForValue().get("UID"));
        //是不是来访者
        Boolean isVistor = movementServiceApi.isvisitor(visitor,userId);
        if (!isVistor){
            //不是再次访问者 ，保存访问者数据
            Visitors visitors=new Visitors();
            visitors.setUserId(userId);
            visitors.setVisitorUserId(visitor);
            visitors.setDate(System.currentTimeMillis());
            visitors.setFrom("首页");
//            visitors.setVisitDate(new SimpleDateFormat("yyyyMMdd").format(new Date(System.currentTimeMillis())));
            //当前用户和游客的缘分值,游客是是visitor，用户是uid
            Integer score = movementServiceApi.haveScore(visitors,userId);
            if (ObjectUtil.isEmpty(score)){
                visitors.setScore(66);
            }else {visitors.setScore(score);}
            //保存数据
            movementServiceApi.saveVisitor(visitors);

        }else {
            //更新数据中的参观时间。
        }*/
        //记录谁看过我的动态，我访问其他人，我是访问者，其他人是登录者，可以在界面上看到记录，



        return ResponseEntity.ok(pageResult);
    }
//好友动态
    public ResponseEntity friendMove(int page, int pagesize) {
        //1.获得登录者id
        String uid = stringRedisTemplate.opsForValue().get("UID");
        //2.根据登录者的id,查找朋友的ids列表,通过朋友的id，查找他的动态和详细信息
        List<Movement>items=movementServiceApi.getFriend(uid,page,pagesize);
        //3. 判断是否为空
        //4.得到每一个动态的id，用来获得详细信息，组成一个集合
        List<Long> ids = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long,UserInfo> infoMap=userInfoServiceApi.findByIds(ids,null);
        //5.循环，根据用户id来封装信息和动态对象，返回数据
        List<MovementsVo>movementsVoList=new ArrayList<>();
        for (Movement item : items) {
            UserInfo userInfo = infoMap.get(item.getUserId());
            MovementsVo init = MovementsVo.init(userInfo, item);
            if (ObjectUtil.isEmpty(init.getLoveCount())){init.setLoveCount(0);}
            if (ObjectUtil.isEmpty(init.getCommentCount())){init.setCommentCount(0);}
            if (ObjectUtil.isEmpty(init.getLikeCount())){init.setLikeCount(0);}
            movementsVoList.add(init);
        }
//        return ResponseEntity.ok(null);
        PageResult pageResult=new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setCounts(movementsVoList.size());
        pageResult.setPages(pageResult.getCounts()/pagesize);

        pageResult.setItems(movementsVoList);
        return ResponseEntity.ok(pageResult);
    }
//单条动态
    public ResponseEntity movebyid(Long id) {
        ObjectId objectId=new ObjectId(Convert.toStr(id));
        Movement movement = movementServiceApi.getmoveById(objectId);
        if (ObjectUtil.isEmpty(movement)){
            return ResponseEntity.ok(null);
        }
        Long userId = movement.getUserId();
        System.out.println(userId);
        UserInfo userInfo = userInfoServiceApi.findById(userId);
            MovementsVo init = MovementsVo.init(userInfo, movement);
            if (ObjectUtil.isEmpty(init.getLoveCount())){init.setLoveCount(0);}
            if (ObjectUtil.isEmpty(init.getCommentCount())){init.setCommentCount(0);}
            if (ObjectUtil.isEmpty(init.getLikeCount())){init.setLikeCount(0);}
        return ResponseEntity.ok(init);
    }

    public PageResult findRecommendMovements(Integer page, Integer pagesize) {
        List<Movement> movlist=new ArrayList<>();
        //推荐动态
        //1,从redis中查看数据有就推荐，无则随机
        String uid = stringRedisTemplate.opsForValue().get("UID");
        String movementsRecommed = stringRedisTemplate.opsForValue().get(Constants.MOVEMENTS_RECOMMEND + uid);
        if (movementsRecommed!=null){
            //推荐的
            //当当前页面数据不满时，返回新的页面
            String[] split = movementsRecommed.split(",");
            if ((page-1)*pagesize>split.length){
                return new PageResult();
            }
            //我们所有要的数据数量
            List<Long> longList = Arrays.stream(split)
                    .skip((page - 1) * pagesize)
                    .limit(pagesize)
                    .map(e -> Convert.toLong(e))
                    .collect(Collectors.toList());

            movlist = movementServiceApi.findRecommendMovements(longList);
        }else {
        //2.随机生成10条动态
        int count=10;
            movlist=movementServiceApi.randomCount(count);
        }
        //3,做总结
        PageResult pageResult = pageResultBymovements(movlist, page, pagesize);
        return pageResult;
    }

//根据每一条动态完善信息
    public PageResult pageResultBymovements(List<Movement> move,Integer page,Integer pagesize){
        List<MovementsVo> list=new ArrayList<>();
        if (move==null){
            return new PageResult(page,pagesize);
        }
        //3. 判断动态有无，分装对象
        for (Movement movement : move) {
            UserInfo userInfo = userInfoServiceApi.findById(movement.getUserId());
            MovementsVo init = MovementsVo.init(userInfo, movement);
            if (ObjectUtil.isEmpty(init.getLoveCount())){init.setLoveCount(0);}
            if (ObjectUtil.isEmpty(init.getCommentCount())){init.setCommentCount(0);}
            if (ObjectUtil.isEmpty(init.getLikeCount())){init.setLikeCount(0);}
            list.add(init);
        }
        PageResult pageResult=new PageResult();
        pageResult.setPage(page);
        pageResult.setPagesize(pagesize);
        pageResult.setCounts(list.size());
        pageResult.setPages(pageResult.getCounts()/pagesize);

        pageResult.setItems(list);
        return pageResult;
    }

    public Integer likeComment(String movementId) {
        return movementServiceApi.likeComment(new ObjectId(movementId));
    }




}

